package com.example.opengldemo._camera_demo;

import android.opengl.EGLSurface;
import android.opengl.GLES30;

import com.example.opengldemo._camera_demo.core.IObserver;
import com.example.opengldemo._camera_demo.renderer.BaseFilter;
import com.example.opengldemo._camera_demo.renderer.LazyFilter;
import com.example.opengldemo._camera_demo.renderer.RenderBean;
import com.example.opengldemo.util.MatrixUtils;

public class SurfaceShower implements IObserver<RenderBean> {

    private Object mSurface;
    private EGLSurface mShowSurface;
    private RenderBean mBean;
    private boolean isShow=false;
    private int mWidth;
    private int mHeight;
    private BaseFilter mFilter;
    private int mMatrixType= MatrixUtils.TYPE_CENTERCROP;
    private OnDrawEndListener mListener;
    @Override
    public void onCall(RenderBean rb) {
        if(rb.endFlag){
            clearSurface();
        }else if(isShow&&mSurface!=null){
            if(mShowSurface==null){
                mBean = rb;
                mShowSurface=rb.egl.createWindowSurface(mSurface);

                mFilter=new LazyFilter();
                mFilter.create();
                mFilter.sizeChanged(rb.sourceWidth, rb.sourceHeight);
                MatrixUtils.getMatrix(mFilter.getVertexMatrix(),mMatrixType,rb.sourceWidth,rb.sourceHeight,
                        mWidth,mHeight);
                MatrixUtils.flip(mFilter.getVertexMatrix(),false,true);
            }
            rb.egl.makeCurrent(mShowSurface);
            GLES30.glViewport(0,0,mWidth,mHeight);
            mFilter.draw(rb.textureId);
            if(mListener!=null){
                mListener.onDrawEnd(mShowSurface,rb);
            }
            rb.egl.swapBuffers(mShowSurface);
        }
    }
    public void setOutputSize(int width,int height){
        this.mWidth=width;
        this.mHeight=height;
    }

    public void setSurface(Object surface){
        this.mSurface=surface;
        clearSurface();
    }
    private void clearSurface() {
        if(mShowSurface!=null){
            mBean.egl.destroySurface(mShowSurface);
            mShowSurface = null;
        }
    }
    public void open(){
        isShow=true;
    }
    public void close(){
        isShow=false;
    }
    /**
     * 设置单帧渲染完成监听器
     * @param listener 监听器
     */
    public void setOnDrawEndListener(OnDrawEndListener listener){
        this.mListener=listener;
    }

    public interface OnDrawEndListener{
        /**
         * 渲染完成通知
         * @param surface 渲染的目标EGLSurface
         * @param bean 渲染用的资源
         */
        void onDrawEnd(EGLSurface surface,RenderBean bean);
    }
}
